<template>
    <el-dialog
        v-model="visible"
        title="修改头像"
        width="400px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
        <div class="avatar-upload-container">
            <div class="avatar-preview">
                <el-avatar 
                    :size="120" 
                    :src="previewUrl || currentAvatarUrl" 
                    class="preview-avatar"
                />
                <div class="avatar-overlay" v-if="previewUrl">
                    <el-icon class="preview-icon"><View /></el-icon>
                </div>
            </div>
            
            <div class="upload-actions">
                <el-upload
                    ref="uploadRef"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="handleFileChange"
                    accept="image/*"
                    class="avatar-uploader"
                >
                    <el-button type="primary" :icon="Plus">选择图片</el-button>
                </el-upload>
                
                <el-button 
                    v-if="previewUrl" 
                    @click="clearSelection" 
                    :icon="Delete"
                    plain
                >
                    重新选择
                </el-button>
            </div>
            
            <div class="upload-tips">
                <p>支持 JPG、PNG、GIF 格式，文件大小不超过 2MB</p>
            </div>
        </div>
        
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button 
                    type="primary" 
                    @click="uploadAvatar" 
                    :loading="uploading"
                    :disabled="!previewUrl"
                >
                    确认上传
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Plus, Delete, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { fileApi } from '../api/file'
import { userApi } from '../api/user'
import { useUserStore } from '../stores/user'

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()
const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

const currentAvatarUrl = computed(() => userStore.userInfo?.avatarUrl || 'https://randomuser.me/api/portraits/men/32.jpg')

const uploadRef = ref()
const previewUrl = ref('')
const selectedFile = ref(null)
const uploading = ref(false)

const handleFileChange = (file) => {
    // 验证文件类型
    const isImage = file.raw.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('请选择图片文件')
        return
    }
    
    // 验证文件大小 (2MB)
    const isLt2M = file.raw.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB')
        return
    }
    
    selectedFile.value = file.raw
    previewUrl.value = URL.createObjectURL(file.raw)
}

const clearSelection = () => {
    selectedFile.value = null
    if (previewUrl.value) {
        URL.revokeObjectURL(previewUrl.value)
        previewUrl.value = ''
    }
    if (uploadRef.value) {
        uploadRef.value.clearFiles()
    }
}

const uploadAvatar = async () => {
    if (!selectedFile.value) {
        ElMessage.warning('请先选择图片')
        return
    }
    
    if (!userStore.userId) {
        ElMessage.error('用户ID获取失败，请重新登录')
        return
    }
    
    console.log('上传文件信息:', {
        fileName: selectedFile.value.name,
        fileSize: selectedFile.value.size,
        fileType: selectedFile.value.type,
        userId: userStore.userId
    })
    
    uploading.value = true
    try {
        // 先上传文件
        const uploadResponse = await fileApi.uploadFile(selectedFile.value, userStore.userId)
        
        if (uploadResponse.data.code === 1000) {
            // 获取上传后的文件ID，构建下载URL
            const fileId = uploadResponse.data.data.id
            const newAvatarUrl = `http://localhost:5032/api/File/download/${fileId}`
            
            if (fileId) {
                // 调用用户API更新头像URL
                const updateResponse = await userApi.changeAvatarUrl(userStore.userId, newAvatarUrl)
                
                if (updateResponse.data.code === 1000) {
                    ElMessage.success('头像修改成功')
                    
                    // 重新获取用户信息以确保数据同步
                    await userStore.fetchUserInfo()
                    
                    // 触发全局事件，通知其他组件刷新数据
                    window.dispatchEvent(new CustomEvent('avatar-updated', {
                        detail: { userId: userStore.userId, newAvatarUrl }
                    }))
                    
                    emit('success', { fileData: uploadResponse.data.data, userData: updateResponse.data.data })
                    close()
                } else {
                    ElMessage.error(updateResponse.data.msg || '更新头像信息失败')
                }
            } else {
                ElMessage.error('获取上传文件URL失败')
            }
        } else {
            ElMessage.error(uploadResponse.data.msg || '文件上传失败')
        }
    } catch (error) {
        console.error('上传头像失败:', error)
        if (error.response) {
            console.error('错误响应:', error.response.data)
            console.error('错误详情:', JSON.stringify(error.response.data, null, 2))
            
            // 显示详细的验证错误
            if (error.response.data?.errors) {
                const errorMessages = Object.values(error.response.data.errors).flat()
                ElMessage.error(`验证错误: ${errorMessages.join(', ')}`)
            } else {
                ElMessage.error(`上传失败: ${error.response.data?.title || error.response.data?.detail || '未知错误'}`)
            }
        } else {
            ElMessage.error('上传失败，请重试')
        }
    } finally {
        uploading.value = false
    }
}

const close = () => {
    clearSelection()
    visible.value = false
}

// 组件卸载时清理URL
import { onUnmounted } from 'vue'
onUnmounted(() => {
    if (previewUrl.value) {
        URL.revokeObjectURL(previewUrl.value)
    }
})
</script>

<style scoped>
.avatar-upload-container {
    text-align: center;
}

.avatar-preview {
    position: relative;
    display: inline-block;
    margin-bottom: 20px;
}

.preview-avatar {
    border: 2px solid #e0e0e0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.3s;
}

.avatar-preview:hover .avatar-overlay {
    opacity: 1;
}

.preview-icon {
    color: white;
    font-size: 24px;
}

.upload-actions {
    margin-bottom: 16px;
    display: flex;
    gap: 12px;
    justify-content: center;
}

.avatar-uploader {
    display: inline-block;
}

.upload-tips {
    color: #909399;
    font-size: 12px;
    line-height: 1.4;
}

.upload-tips p {
    margin: 0;
}

.dialog-footer {
    text-align: right;
}
</style> 